package cc.ipost.ipost;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import cc.ipost.ipost.data.RequestData;

public class WebServiceTask extends AsyncTask<Object, Object, String> {
	private RequestData rd;
	private Handler handler;
	private JSONObject response;

	public WebServiceTask(RequestData rd, Handler handler) {
		this.rd = rd;
		this.handler = handler;
	}

	@Override
	protected String doInBackground(Object... arg0) {
		WebService ws = new WebService(rd);
		HttpResponse res = ws.request();
		Log.i("WebServiceTask", "response: " + res);
		if (res != null) {
			try {
				response = new JSONObject(EntityUtils.toString(res.getEntity()));
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else {
			response = null;
		}
		return "";
	}

	@Override
	protected void onPostExecute(String result) {
		if (response != null) {
			try {
				int code = response.getInt("code");
				Message msg;
				if (code == 0) {
					msg = handler.obtainMessage(MySettings.SUCCESS);
					msg.obj = response;
				} else {
					msg = handler.obtainMessage(MySettings.ERR);
					msg.obj = response.getString("msg");
				}
				handler.sendMessage(msg);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else {
			handler.sendEmptyMessage(MySettings.FAIL);
		}

	}

}
